﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KeyboardImageViewer
{
    public class DirectorySet
    {
        public DirectorySet()
        {
            this.BaseDirectories = new List<BaseDirectory>();
        }

        public List<BaseDirectory> BaseDirectories { get; set; }

        public bool PathIsIncluded(string path)
        {
            path = path.ToLowerInvariant();

            bool included = false;

            foreach (BaseDirectory baseDirectory in this.BaseDirectories)
            {
                if (!baseDirectory.Missing && path.StartsWith(baseDirectory.Path.ToLowerInvariant()))
                {
                    included = true;

                    foreach (string excludedPath in baseDirectory.Exclusions)
                    {
                        if (path.StartsWith(excludedPath.ToLowerInvariant()))
                        {
                            included = false;
                            break;
                        }
                    }

                    break;
                }
            }

            return included;
        }

        public bool Equals(DirectorySet otherDirectorySet)
        {
            if (this.BaseDirectories.Count != otherDirectorySet.BaseDirectories.Count)
            {
                return false;
            }

            for (int i = 0; i < this.BaseDirectories.Count; i++)
            {
                if (this.BaseDirectories[i].Missing != otherDirectorySet.BaseDirectories[i].Missing)
                {
                    return false;
                }

                if (this.BaseDirectories[i].Path != otherDirectorySet.BaseDirectories[i].Path)
                {
                    return false;
                }

                if (this.BaseDirectories[i].Exclusions.Count != otherDirectorySet.BaseDirectories[i].Exclusions.Count)
                {
                    return false;
                }

                for (int j = 0; j < this.BaseDirectories[i].Exclusions.Count; j++)
                {
                    if (this.BaseDirectories[i].Exclusions[j] != otherDirectorySet.BaseDirectories[i].Exclusions[j])
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        public string GetRelativeName(string filePath)
        {
            string filePathLower = filePath.ToLowerInvariant();

            foreach (BaseDirectory baseDirectory in this.BaseDirectories)
            {
                if (filePathLower.StartsWith(baseDirectory.Path.ToLowerInvariant()))
                {
                    return filePath.Substring(baseDirectory.Path.Length + 1);
                }
            }

            return null;
        }
    }
}
